package com.saint.swipemenulistview.courier;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.os.StatFs;
import android.provider.BaseColumns;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.provider.MediaStore.MediaColumns;
import android.support.v4.app.ActivityCompat;
import android.widget.Toast;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class BaseCommUtils {

	/** 调用相机和图库 */
	public static Dialog getSystemImg(final Context c, final Activity act, final String userIndex) {
		String[] items = new String[]{"相机", "图库"};
		Builder alert = new Builder(c);
		alert.setCancelable(true);
		alert.setTitle("请选择下列选项");
		alert.setItems(items, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
					case 0:
						getCamera(c, act, 1, userIndex);
						break;
					case 1:
						getPhoto(act, 2);
						break;
					default:
						break;
				}
			}
		});
		Dialog dialog = alert.create();
		dialog.show();
		return dialog;
	}

	/** 调用android自带的照相机 */
	public static void getCamera(Context c, Activity act, int requestCode, String userIndex) {
		File file = new File(BaseConfig.BASE_IMG_CACHE);
		if (!file.exists()) {
			try {
				file.mkdirs();
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

		// 判断存储卡是否可以用，可用进行存储,可用存储控件大于10M才能拍照
		if (hasSdcard() && getSDFreeSize() > 10) {
			try {
				if (isCameraPermission(c)) {
					String path = BaseConfig.BASE_IMG_CACHE + userIndex + ".jpg";
					intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(path)));
					intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);// 这里添加拍摄低质量图片配置
					act.startActivityForResult(intent, requestCode);

				} else {
					Toast.makeText(c, "摄像头权限被禁止", Toast.LENGTH_LONG).show();
				}

			} catch (Exception e) {
				e.printStackTrace();
				Toast.makeText(c, "摄像头权限被禁止", Toast.LENGTH_LONG).show();
			}

		} else if (getSDFreeSize() <= 10) {
			Toast.makeText(c, "存储空间不足", Toast.LENGTH_LONG).show();
		} else {
			Toast.makeText(c, "内存卡不可用", Toast.LENGTH_LONG).show();
		}

	}

	/** 调用android自带的照相机 */
	public static void getCamera(Activity act, int requestCode, String imagePath) {
//		File file = new File(BaseConfig.BASE_IMG_CACHE);
//		if (!file.exists()) {
//			try {
//				file.mkdirs();
//			} catch (Exception e) {
//				// TODO: handle exception
//			}
//		}
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

		// 判断存储卡是否可以用，可用进行存储,可用存储控件大于10M才能拍照
		if (hasSdcard() && getSDFreeSize() > 10) {
//			try {
				if (isCameraPermission(act)) {
//					String path = BaseConfig.BASE_IMG_CACHE + userIndex + ".jpg";
					intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(imagePath)));
					intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);// 这里添加拍摄低质量图片配置
					act.startActivityForResult(intent, requestCode);

				} else {
					Toast.makeText(act, "摄像头权限被禁止", Toast.LENGTH_LONG).show();
				}

//			} catch (Exception e) {
//				e.printStackTrace();
//				Toast.makeText(act, "摄像头权限被禁止", Toast.LENGTH_LONG).show();
//			}

		} else if (getSDFreeSize() <= 10) {
			Toast.makeText(act, "存储空间不足", Toast.LENGTH_LONG).show();
		} else {
			Toast.makeText(act, "内存卡不可用", Toast.LENGTH_LONG).show();
		}

	}

	/** 调用android的图库 */
	public static void getPhoto(Activity act, int requestCode) {
		Intent intent = new Intent(Intent.ACTION_PICK, Images.Media.EXTERNAL_CONTENT_URI);//
		act.startActivityForResult(intent, requestCode);
	}

	/**
	 * 检查是否存在SDCard
	 *
	 * @return
	 */
	public static boolean hasSdcard() {
		String state = Environment.getExternalStorageState();
		if (state.equals(Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 检测sd卡可用空间
	 */
	public static long getSDFreeSize() {
		// 取得SD卡文件路径
		File path = Environment.getExternalStorageDirectory();
		StatFs sf = new StatFs(path.getPath());
		// 获取单个数据块的大小(Byte)
		long blockSize = sf.getBlockSize();
		// 空闲的数据块的数量
		long freeBlocks = sf.getAvailableBlocks();
		// 返回SD卡空闲大小
		// return freeBlocks * blockSize; //单位Byte
		// return (freeBlocks * blockSize)/1024; //单位KB
		return (freeBlocks * blockSize) / 1024 / 1024; // 单位MB
	}

	public static Bitmap rotateBitmap(String filePath, Bitmap bitmap) {
		try {
			int degree = 0;
			ExifInterface exifInterface = new ExifInterface(filePath);
			int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
			switch (orientation) {
				case ExifInterface.ORIENTATION_ROTATE_90:
					degree = 90;
					break;
				case ExifInterface.ORIENTATION_ROTATE_180:
					degree = 180;
					break;
				case ExifInterface.ORIENTATION_ROTATE_270:
					degree = 270;
					break;
			}

			Matrix matrix = new Matrix();
			matrix.postRotate(degree);
			// 创建新的图片
			return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
		} catch (Throwable e) {
			e.printStackTrace();
			return bitmap;
		}

	}

	public static String getImgUrl(Uri uri, Activity act) {

		String res = null;
		String[] proj = {MediaColumns.DATA};
		Cursor cursor = act.getContentResolver().query(uri, proj, null, null, null);
		if (cursor.moveToFirst()) {

			int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
			res = cursor.getString(column_index);
		}
		cursor.close();
		return res;

	}

	// 检测摄像机权限是否可用
	public static boolean isCameraPermission(Context context) {
		try {

			Camera.open().release();
			return true;
		} catch (Exception e) {
			return false;
		}

	}

	public static String getVideoUrl(Uri uri, Activity act) {
		String res = null;
		Uri uri1 = Uri.parse(uri.toString().replace("%3A", "/"));
		String[] proj = {MediaColumns.DATA};
		Cursor cursor = act.getContentResolver().query(uri1, proj, null, null, null);
		if (cursor.moveToFirst()) {

			int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);

			res = cursor.getString(column_index);
		}
		cursor.close();
		return res;
	}

	/** 4.4 */
	@SuppressLint("NewApi")
	public static String getVideoUrlNew(Uri uri, Activity act) {
		String filePath = null;
		try {
			String wholeID = DocumentsContract.getDocumentId(uri);
			// 获得资源唯一ID
			String id = wholeID.split(":")[1];
			// 定义索引字段
			String[] column = {MediaColumns.DATA};

			//
			String sel = BaseColumns._ID + "=?";
			Cursor cursor = act.getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, column, sel, new String[]{id}, null);

			int columnIndex = cursor.getColumnIndex(column[0]);
			if (cursor.moveToFirst()) {
				// DATA字段就是本地资源的全路径
				filePath = cursor.getString(columnIndex);
			}
			// 关闭游标
			cursor.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return filePath;
	}

	/**
	 *
	 * 根据视频Uri地址取得指定的视频缩略图
	 *
	 * @param cr
	 * @param uri
	 *            本地视频Uri标示
	 * @return 返回bitmap类型数据
	 */

	public static Bitmap getVideoThumbnail(ContentResolver cr, Uri uri) {
		Bitmap bitmap = null;
		Options options = new Options();
		options.inDither = false;
		options.inPreferredConfig = Config.ARGB_8888;
		Cursor cursor = cr.query(uri, new String[]{BaseColumns._ID}, null, null, null);

		if (cursor == null || cursor.getCount() == 0) {
			return null;
		}
		cursor.moveToFirst();
		String videoId = cursor.getString(cursor.getColumnIndex(BaseColumns._ID));

		if (videoId == null) {
			return null;
		}
		cursor.close();
		long videoIdLong = Long.parseLong(videoId);
		bitmap = MediaStore.Video.Thumbnails.getThumbnail(cr, videoIdLong, Images.Thumbnails.MICRO_KIND, options);

		return bitmap;
	}

	public static int getAndroidSDKVersion() {
		int version = 0;
		try {
			version = Integer.valueOf(android.os.Build.VERSION.SDK);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return version;
	}

	/** 返回汉字 */
	public static String numToChinese(int num) {
		if (num > 0 && num < 13) {
			String[] array = {"一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二"};
			return array[num - 1];
		} else {
			return num + "";
		}

	}

//	public static void MakeACall(Activity act, String tel) {
//		// 传入服务， parse（）解析号码
//		Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + tel));
//		// 通知activtity处理传入的call服务
//		if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
//			// TODO: Consider calling
//			//    ActivityCompat#requestPermissions
//			// here to request the missing permissions, and then overriding
//			//   public void onRequestPermissionsResult(int requestCode, String[] permissions,
//			//                                          int[] grantResults)
//			// to handle the case where the user grants the permission. See the documentation
//			// for ActivityCompat#requestPermissions for more details.
//			return;
//		}
//		act.startActivity(intent);
//	}

	// 图片按比例大小压缩方法（根据路径获取图片并压缩）
	public static Bitmap getimage(String srcPath) {
		if (srcPath == null) {
			return null;
		}
		File file = new File(srcPath);
		Options newOpts = new Options();
		// 开始读入图片，此时把options.inJustDecodeBounds 设回true了
		newOpts.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);// 此时返回bm为空

		newOpts.inJustDecodeBounds = false;
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;
		// 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
		// int hh = 800;// 这里设置高度为800f
		// int ww = 480;// 这里设置宽度为480f
		float hh = 400f;// 这里设置高度为800f
		float ww = 240f;// 这里设置宽度为480f
		// 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
		int be = 1;// be=1表示不缩放
		// 这样压缩方法，听说更合理
		be = (int) ((w / ww + h / hh) / 2);
		if (be <= 0)
			be = 1;

		newOpts.inSampleSize = be;// 设置缩放比例
		newOpts.inPreferredConfig = Config.RGB_565;
		newOpts.inPurgeable = true;// 设置可清除
		newOpts.inInputShareable = true;// 和上面一起使用才起作用
		// 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了

		bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
		if (bitmap == null) {
			return null;// 破损图片
		} else {
			return compressImage(bitmap);// 压缩好比例大小后再进行质量压缩
		}
		// return bitmap;
	}

	// 质量压缩方法
	public static Bitmap compressImage(Bitmap image) {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		// 把png压缩格式改为jpeg
		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
		// 不从100开始，以免浪费一次压缩次数，100表示不压缩
		int options = 90;
		while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
			baos.reset();// 重置baos即清空baos
			image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
			// if (options <= 10||options>0) {
			// options -= 1;
			// } else {
			// options -= 10;// 每次都减少10
			// }
			// 上面逻辑问题，压缩太慢.以下这种方法，能够处理10M图片压缩到100k多一点
			if (options > 10) {
				options -= 10;// 每次都减少10
			} else if (options >= 2 && options <= 10) {
				options--;
			} else {
				break;
			}

		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中

		/* 201607141849 */
		Options opt = new Options();
		opt.inPreferredConfig = Config.RGB_565; // 减少图片质量，防止内存溢出
		opt.inPurgeable = true;// 设置可清除
		opt.inInputShareable = true;// 和上面一起使用才起作用

		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, opt);// 把ByteArrayInputStream数据生成图片

		return bitmap;
	}

	/**
	 * 保存文件
	 * 
	 * @param bm
	 * @param fileName
	 * @throws IOException
	 */
	public static void saveFile(Bitmap bm, String fileName) throws IOException {
		String path = fileName;
		File dirFile = new File(path);
		if (!dirFile.exists()) {
			dirFile.mkdir();
		}
		File myCaptureFile = new File(path + fileName);
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
		bos.flush();
		bos.close();
	}
}
